'use server';

import {
  categoryNameToPathString,
  getCategoryFullPaths,
} from '@/utils/common/product';
import { cache } from 'react';
import { gfetch } from '@/utils/back/fetch';

function getObjectSizeInBytes(obj: Obj) {
  const jsonString = JSON.stringify(obj);
  const encoder = new TextEncoder();
  const byteArray = encoder.encode(jsonString);
  return byteArray.length;
}

const fetchServerSideCategories = cache(async () => {
  // const authHeader = headers().get('authorization')
  const res = await gfetch('/public/categories');
  // console.log(res);
  // console.log('Size: ', getObjectSizeInBytes(res));
  if (res.success && res.data instanceof Array) {
    // console.log('🔎 ✔️ ===> Categories >', res.data?.length);
    return res.data;
  }
  // else if (!res.success) {
  //   await sleep(1);
  //   console.log('🔎 ❌ ===> MOCK Categories >', mockCategory?.length);
  //   return mockCategory;
  // }
  else {
    return [];
  }
});

const tempCache = new Map();
const cacheKey = 'categories';
const cacheTTL = 3600 * 1000;

export const getServerSideCategories = async () => {
  const now = Date.now();
  if (tempCache.has(cacheKey)) {
    const { data, expires } = tempCache.get(cacheKey);
    if (now < expires) {
      //console.log('🔎 Get categories from cache ⏰');
      return data;
    } else {
      tempCache.delete(cacheKey);
    }
  }
  const startTime = Date.now();
  const res = await fetchServerSideCategories();
  // console.log(
  //   '🔎 a. Get Categories - spend time:',
  //   ((Date.now() - startTime) / 1000).toFixed(3)
  // );
  if (res?.length) {
    const startTime = Date.now();
    /* **********
    Preprocess the categories list to prepare for the later work such as route matching classification
    ********** */
    const list = res.map((c: Obj) => {
      const formatPath = getCategoryFullPaths(c, res)?.paths;
      return {
        ...c,
        format_title: categoryNameToPathString(c.title),
        format_paths: formatPath.map(e => e.n).join('/'),
      };
    });
    tempCache.set(cacheKey, { data: list, expires: Date.now() + cacheTTL });
    // console.log(
    //   '🔎 b. Deal Categories - spend time:',
    //   ((Date.now() - startTime) / 1000).toFixed(3)
    // );
    return list;
  }
  return res;
};
